package com.xunmall.gateway.interceptor.security;

import com.xunmall.base.util.StringUtils;
import org.assertj.core.util.Arrays;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Created by Gimgoog on 2018/1/29.
 */
public class SecCheckFilter implements Filter {

    private String[] XssExcludePaths;	// 不进行XSS转码的url

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        String requestUri = request.getRequestURI();
        String contentPath = request.getContextPath();

        // 防止脚本注入，对request做转码
        if (requestUri != null) {
            requestUri = requestUri.replaceFirst(contentPath, "");
            if (!excludeUrl(XssExcludePaths, requestUri)) {
                // XssEncoderHttpRequest用于常见的注入字符的自动转码,XssExcludePaths中url的不处理
                request = new XssEncoderHttpRequest((HttpServletRequest)req, null);
            }
        }

        filterChain.doFilter(request, response);
    }
    private boolean excludeUrl(String[] paths, String url) {
        if (!StringUtils.isEmpty(url) && !Arrays.isNullOrEmpty(paths)) {
            for (String path : paths) {
                if (url.toLowerCase().startsWith(path)) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        String xssExcludePath = config.getInitParameter("xssExcludePaths");
        if (!StringUtils.isEmpty(xssExcludePath)) {
            XssExcludePaths = xssExcludePath.toLowerCase().split(",");
        }
    }
}
